import io
import json
import flask
import requests
import argparse
import torch
import torch.nn.functional as F
from PIL import Image
from torchvision import transforms as T
from torchvision.models import resnet50
from torch.autograd import Variable

PyTorch_REST_API_URL = 'http://127.0.0.1:5000/predict'

def predict_result(image_path):
    image = open(image_path,"rb").read()
    payload = {"image":image}

    try:
        r = requests.post(PyTorch_REST_API_URL, files=payload).json()
    except requests.exceptions.JSONDecodeError as e:
        print("JSON Decode Error:", e)
        print("Response Text:", r.text)

    if r["success"]:
        for (i,result) in enumerate(r["predictions"]):
            print("{}.  {}.  {:.4f}".format(i+1,result['label'],result['probability']))
    else:
        print("Request Failed")


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Classification demo")
    parser.add_argument("--file",type=str,help="test image file")

    args = parser.parse_args()
    predict_result(args.file)
